import json
from datetime import datetime
from helper.common import logger

class HTML_Generator:
    def __init__(self, data_dir):
        self.__date_str = datetime.now().strftime("%Y-%m-%d")
        self.__data_dir = data_dir
        self.__json_file = f'{self.__data_dir}answers_{self.__date_str}.json'

    def __read_data(self):
        with open(self.__json_file, 'r', encoding='utf-8') as file:
            return json.load(file)

    def __generate_html(self, data):
        html_content = """
        <!DOCTYPE html>
        <html lang="zh">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>每日练习</title>
            <style>
                .answer {
                    display: none;
                }
                input[type="checkbox"]:checked + label + .answer {
                    display: block;
                }
            </style>
        </head>
        <body>
        <p>哦哈哟~ 这是今天的题目哦٩(•̤̀ᵕ•̤́๑)ᵒᵏᵎᵎᵎᵎ</p>
        <p>请先思考，再点击查看答案喵😊</p>
        <br>
        """
        for category, questions in data.items():
            html_content += f'<p>【{category}】<p>\n'
            for idx, (question, answer) in enumerate(questions.items()):
                answer_id = f"answer_{category}_{idx}"
                html_answer = answer.replace('\n', '<br>')
                html_content += f'<div>\n'
                html_content += f'<input type="checkbox" id="{answer_id}" />\n'
                html_content += f'<label for="{answer_id}"><strong>{question}</strong></label>\n'
                html_content += f'<div class="answer">{html_answer}</div>\n'
                html_content += '</div>\n'
        html_content += """
        <p>答案来自文心一言ERNIE-3.5模型 仅供参考</p>
        </body>
        </html>
        """
        return html_content

    def __save_html(self, html_content):
        filename = f'{self.__data_dir}answers_{self.__date_str}.html'
        with open(filename, 'w', encoding='utf-8') as file:
            file.write(html_content)
        logger.info(f"File '{filename}' has been saved at {self.__data_dir}")
        return filename

    def generate(self):
        try:
            data = self.__read_data()
            html_content = self.__generate_html(data)
            return self.__save_html(html_content)
        except Exception as e:
            logger.error(f"HTML generate error: {e}")
            return None